package info.DanielL.onceuponatime;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



/**
 * Servlet implementation class Home
 * 
 * @author Daniel Lacasta
 * @version 1.0
 */
@WebServlet("/Home")
public class Home extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Home() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		redirectHome(request, response);
	}

	private void redirectHome(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		//Get tales from database
		String tales = getTales();
		
		//We set tales attribute for the jsp
		request.setAttribute("tales", tales);
		
		// Just redirect to home.jsp
		this.getServletContext().
			getRequestDispatcher("/home.jsp").forward(request,response);
	}

	/**
	 * gets all tales from database
	 * @return
	 */
	private String getTales() {
		String allTales = "";
		int id= 0;
		String urlcon = "jdbc:mysql://localhost:3306/onceupon";
		
		try {
			Class.forName("com.mysql.jdbc.Driver");
			Connection conn = 
					DriverManager.getConnection(urlcon, "root","");
					Statement stat = conn.createStatement();
					ResultSet resultSet = stat.executeQuery("Select * from tale");
					
					while(resultSet.next()){
						id = resultSet.getInt("id");
						allTales += resultSet.getString("title");
						allTales+= " | < href='Delete?id="+id+"'>Delete</a>";
						allTales+= " | < href='Update?id="+id+"'>Update</a>";
						allTales+="<br />";
					}
					
					resultSet.close();
					conn.close();
		} catch (Exception e) {
			
			 e.printStackTrace();
			 return ("Error: " + e.getMessage());
		}
		
				
		allTales = "";
		
		return allTales;
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
